package emby.stmt;

import emby.ASTNode;
import emby.EmbyRuntime;
import emby.expr.Expression;
import emby.lang.Block;
import emby.lang.Scope;
import emby.writer.IEmbyCodifier;

public class For extends Statement{

	private static final long serialVersionUID = 1523705250018092652L;
	ASTNode initializer;
	Expression condition;
	ASTNode accumulator;
	Block body;
	public For(ASTNode initializer, Expression _condition, ASTNode accumulator, Block _body){
		this.initializer=initializer;
		condition = _condition;
		this.accumulator=accumulator;
		body = _body;
	}

	/**
	 * Always returns null UNLESS there was a return statement in the block.
	 */
	@Override
	public Object eval(Scope s) {
		//Scope subscope = new Scope(s);
		if(EmbyRuntime.echo){
			emby.util.Print.println("Evaluating for loop. Condition: "+condition+" init: "+initializer+" acc: "+accumulator);
		}
		for( initializer.eval(s); If.isConditionTrue(condition,s); accumulator.eval(s)){
			Object retValue = body.eval(s);
			if(retValue!=null){
				return retValue;
			}
		}
		return null;
	}
	
	public void codify(IEmbyCodifier ec){
		ec.for_(initializer, condition, accumulator, body);
	}
}